<!--
 * @Date: 2025-04-27 10:58:57
 * @LastEditors: Csir 2215995096@qq.com
 * @LastEditTime: 2025-05-21 17:41:08
 * @FilePath: \yujin-ui-admin\src\views\opticore\route\components\RouteProcessRelForm.vue
-->
<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <div class="dragg-line" style="height: 40px">
      <div class="index">{{ t('opticore.routeProcessRel.table.column.index') }}</div>
      <div class="item">{{ t('opticore.routeProcessRel.table.column.processCode') }}</div>
      <div class="item">{{ t('opticore.routeProcessRel.table.column.processName') }}</div>
      <div class="item">{{ t('opticore.routeProcessRel.table.column.errorPrevention') }}</div>
      <div class="item">{{ t('table.action') }}</div>
    </div>

    <draggable
      v-model="formData"
      :itemKey="(item) => item.id"
      :animation="200"
      handle=".drag-handle"
    >
      <template #item="{ element }">
        <div class="dragg-line drag-handle">
          <div class="index">{{ element.cid }}</div>
          <div class="item">
            <el-input style="width: 180px" v-model="element.processCode" disabled />
          </div>

          <div class="item">
            <el-select
              v-model="element.processName"
              :placeholder="t('opticore.routeProcessRel.placeholder.processName')"
              style="width: 180px"
              @change="onProcessNameChange(element)"
            >
              <el-option
                v-for="dict in processList"
                :key="dict.processCode"
                :label="dict.processName"
                :value="dict.processName"
              />
            </el-select>
          </div>
          <div class="item">
            <el-switch
              v-model="element.errorPrevention"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeSwitch"
            />
          </div>
          <div class="item">
            <el-button @click="handleDelete(element.cid - 1)" link>{{t('common.action.del')}}</el-button>
          </div>
        </div>
      </template>
    </draggable>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ {{ t('common.button.create') }}</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { RouteApi } from '@/api/opticore/route'
import { ProcessInfoApi, ProcessInfoVO } from '@/api/opticore/processinfo'
import { ref, reactive, watch, onMounted, defineProps, defineExpose } from 'vue'
import draggable from 'vuedraggable'
const { t } = useI18n()

const props = defineProps<{
  routeId: undefined // 工艺路线ID（主表的关联字段）
  switchStatus: Boolean
}>()

const emit = defineEmits(['sendStatus'])

const formLoading = ref(false) // 表单的加载中
const processList = ref<ProcessInfoVO[]>([]) // 存储工序列表
const formData = ref([])
const formRules = reactive({
  processId: undefined,
  processCode: undefined,
  processName: [{ required: true, message: '工序不能为空', trigger: 'blur' }]
  // errorPrevention: [{ required: true, message: '防错不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const tableRef = ref() // 表格 Ref

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.routeId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {
      formLoading.value = true

      const res = await RouteApi.getRouteProcessRelListByRouteId(val)

      let newlist = res.map((item, index) => {
        return {
          ...item,
          errorPrevention: item.errorPrevention == 1 ? true : false,
          cid: index + 1
        }
      })

      formData.value = newlist
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

const allSelect = (val) => {
  formData.value = formData.value.map((item) => {
    return {
      ...item,
      errorPrevention: val ? true : false
    }
  })
}

watch(
  formData,
  (val) => {
    let flagTrue = val.every((item) => {
      return item.errorPrevention == true
    })

    if (flagTrue) {
      emit('sendStatus', true)
    }
  },
  {
    deep: true
  }
)

watch(
  formData,
  (val) => {
    let flagFalse = val.every((item) => {
      return item.errorPrevention == false
    })

    if (flagFalse) {
      emit('sendStatus', false)
    }
  },
  {
    deep: true
  }
)

watch(
  formData,
  (val) => {
    let flagFalse = val.some((item) => {
      return item.errorPrevention == false
    })

    if (flagFalse) {
      emit('sendStatus', false)
    }
  },
  {
    deep: true
  }
)
const changeSwitch = (val) => {
  console.log(val)
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    routeId: undefined,
    processId: undefined,
    errorPrevention: undefined
  }
  row.routeId = props.routeId
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

/** 当工序名称选择变化时的处理逻辑 */
const onProcessNameChange = (row) => {
  console.log('onProcessNameChange======', processList)
  const selectedProcess = processList.value.find(
    (process) => process.processName === row.processName
  )
  if (selectedProcess) {
    row.processCode = selectedProcess.processCode
    row.processId = selectedProcess.id
  }
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 100
})

const getProcessList = async () => {
  console.log('getProcessList======')
  const data = await ProcessInfoApi.getProcessInfoPage(queryParams)
  processList.value = data.list
}

/** 页面挂载时调用获取工序列表 */
onMounted(() => {
  getProcessList()
})

defineExpose({ validate, getData, allSelect })
</script>
<style scoped lang="scss">
.dragg-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  border-bottom: 1px solid #eceff5;
  cursor: pointer;
  .index {
    width: 60px;
  }

  .item:last-child {
    width: 80px;
  }
  .item:nth-child(2) {
    width: 200px;
  }
  .item:nth-child(3) {
    width: 200px;
  }
  .item:nth-child(4) {
    width: 200px;
  }
}
</style>
